﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Domain;
using Casamiel.Domain.Response;
using MediatR;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Casamiel.Application.Commands
{
	/// <summary>
	/// Get product stock list by store identifier command handler.
	/// </summary>
	public sealed class GetProductStockListByStoreIdCommandHandler : IRequestHandler<GetProductStockListByStoreIdCommand, BaseResult<List<GoodsGetListRsp>>>
    {
        /// <summary>
        /// The client factory.
        /// </summary>
        private readonly IHttpClientFactory _clientFactory;
        private readonly IGoodBaseRepository _goodBaseRepository;
        public GetProductStockListByStoreIdCommandHandler(IHttpClientFactory httpClientFactory, IGoodBaseRepository goodBaseRepository)
        {
            _clientFactory = httpClientFactory;
            _goodBaseRepository = goodBaseRepository;
        }
        /// <summary>
        /// Handle the specified request and cancellationToken.
        /// </summary>
        /// <returns>The handle.</returns>
        /// <param name="request">Request.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public async Task<BaseResult<List<GoodsGetListRsp>>> Handle(GetProductStockListByStoreIdCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            var url = "mweb/goods/GetListByIds";
            var ProductList = await _goodBaseRepository.GetProductIDsAsync<ICasaMielSession>(request.StoreId).ConfigureAwait(false);
            if (ProductList == null)
            {
                return new BaseResult<List<GoodsGetListRsp>>(null, 0, "");
            }
            var data = new { productIds = string.Join(',', ProductList.ToArray()) };
            var result = await PostAsync(url, JsonConvert.SerializeObject(data)).ConfigureAwait(false);
            var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
            if (dynamicdata["ResultNo"].ToString() == "00000000")
            {
                var entity = JsonConvert.DeserializeObject<List<GoodsGetListRsp>>(dynamicdata["Data"].ToString());
                return new BaseResult<List<GoodsGetListRsp>>(entity, 0, "");
            }
            return new BaseResult<List<GoodsGetListRsp>>(null, 999, dynamicdata["ResultRemark"].ToString());
        }


        /// <summary>
        /// Posts the async.
        /// </summary>
        /// <returns>The async.</returns>
        /// <param name="url">URL.</param>
        /// <param name="data">Data.</param>
        private async Task<string> PostAsync(string url, string data)
        {
            var client = _clientFactory.CreateClient("storeapi");
            using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, url)
            {
                Content = new StringContent(data, System.Text.Encoding.UTF8, "application/json")
            })
            {
                using (var response = await client.SendAsync(requestMessage).ConfigureAwait(false))
                {

                    if (response.IsSuccessStatusCode)
                    {
                        var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                        return result;
                    }
                    throw new HttpRequestException();
                }
            }


        }
    }


}
